package blue.starter.internal.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.RuntimeBeanReference;

/**
 * @author Jin Zheng
 * @since 1.0 2020-07-30
 */
public class BeanFactoryUtil
{
	private static Logger logger = LoggerFactory.getLogger(BeanFactoryUtil.class);

	private BeanFactoryUtil()
	{
	}

	public static <T> T getBean(BeanFactory factory, String beanName, Class<T> clazz)
	{
		AssertUtil.notNull(factory, "BeanFactory");

		if (beanName == null || beanName.isEmpty())
			return null;

		try
		{
			T bean = factory.getBean(beanName, clazz);
			return bean;
		}
		catch (BeansException e)
		{
			logger.info("Bean [{}] not exist, name: {}", clazz.getSimpleName(), beanName);
			return null;
		}
	}

	public static void addPropertyValue(MutablePropertyValues propertyValues, String property, Object value)
	{
		if (value != null && !"".equals(value))
		{
			propertyValues.addPropertyValue(property, value);
		}
	}

	public static void addPropertyRef(MutablePropertyValues propertyValues, String property, String ref)
	{
		if (ref != null && !"".equals(ref))
		{
			propertyValues.addPropertyValue(property, new RuntimeBeanReference(ref));
		}
	}

}
